package org.ithang.lock;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import redis.clients.jedis.Jedis;

public class RedisLock implements Lock {

	private Random r=new Random(System.currentTimeMillis());
	private Jedis redis=new Jedis("192.168.0.180",6379);
	
	
	@Override
	public void lock() {
		boolean locked=tryLock();
		if(!locked){
			try{
				Thread.sleep(r.nextInt(100));
			}catch(Exception e){
				e.printStackTrace();
			}
			lock();
		}   
	}

	@Override
	public void lockInterruptibly() throws InterruptedException {

	}

	@Override
	public boolean tryLock() {
		try{
            if(1==redis.setnx("lock", "locked")){
            	return true;
            }
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
		return false;
	}

	@Override
	public void unlock() {
		redis.del("lock");
	}

	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}

}
